namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    
	/// <summary>
	/// 1. Start at homepage
	/// 2. Click New Record on top menu bar
	/// 3. Click Account
	/// 4. Enter name
	/// 5. Click Save & Close
	/// </summary>
    
    public class QuickCreateNewAccount : CrmWebTest
    {
        public void QuickCreateNewAccount_PreWebTest(object sender, PreWebTestEventArgs e)
        {
            EntityRequest er = new EntityRequest();
            er.Type = EntityNames.Users;
            er.ReturnAs = EntityNames.Users;
            er.ParentID = EntityManager.Instance.OrgId;

            System.Collections.Hashtable userProps = new System.Collections.Hashtable();
            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                userProps.Add("role", e.WebTest.Context["UserRole"]);
                er.Props = userProps;
            }
            
            System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

            user = (CRMEntity)Entities[EntityNames.Users];

            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            orgId = new Guid(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];            
        }
    
        public void QuickCreateNewAccount_PostWebTest(object sender, PostWebTestEventArgs e)
        {
			try
			{
                if (newAcctId != null)
                {
                    newAcctId = new Guid(newAcctId).ToString();
                    Guid g = EntityManager.Instance.GetOwnerGuid(new Guid(user[EntityIDNames.User]), new Guid(user["OrganizationId"]));
                    EntityManager.Instance.AddEntity(EntityNames.Accounts, g, new string[] { "OwningUser", "AccountID", "name", "EntityManagerOwningUser" }, new string[] { user["systemuserid"], newAcctId, name, g.ToString() });
                }
			}
            catch (System.FormatException fe)
            {
                System.Diagnostics.Trace.WriteLine("AccountId should never be set to anything other than Guid. This should not happen. " + fe.ToString());
            }
			finally
			{
				EntityManager.Instance.FreeEntity(user);
			}
        }

        public QuickCreateNewAccount()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());

            GetContextHtml_Helper.PrimaryContact(out ctxt, out ctxt_formXml, out ctxt_formSubmitId);

            this.Proxy = null;            
            PreWebTest += new EventHandler<PreWebTestEventArgs>(QuickCreateNewAccount_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(QuickCreateNewAccount_PostWebTest);
        }
        
        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            this.BeginTransaction("QuickCreateAccount");

            sfa_accts_edit_aspx dp = new sfa_accts_edit_aspx(user);
            yield return (dp);

            referer = dp.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx f = new _forms_FormScript_js_aspx(user);
            f.etc = 1;
            f.FormType = "main";
            f.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            f.Headers.Add(headerItem);
            yield return (f);

            dp = new sfa_accts_edit_aspx(user);
            name = Utils.GetRandomString(5, 30);
            dp.crmFormSubmitXml = EntityXmlHelper.GetCreateAccountXml(new Guid(user[EntityIDNames.User]), 8, name);

            dp.crmFormSubmitMode = 1;
            dp.CrmFormUserModified = true;
            dp.crmFormSubmitObjectType = 1;
            dp.crmFormSubmitSecurity = 852023;
            dp.crmFormSubmitOnline = 1;
            rpcInfo = Utils.GenerateWRPCToken(sfa_accts_edit_aspx.url, user, tokenKey);
            dp.CRMWRPCToken = rpcInfo.token;
            dp.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;            
            yield return (dp);

			this.EndTransaction("QuickCreateAccount");

            //get the newly created account id out of the post reply
            int idIdx = dp.lastResponse.BodyString.IndexOf(newIdMarker);
            string tempNewAcctId = dp.lastResponse.BodyString.Substring(idIdx + (QuickCreateNewAccount.newIdMarker.Length), 36);
            newAcctId = new Guid(tempNewAcctId).ToString();
        }

        private static RelatedInformation.Context ctxt;
        private static string ctxt_formXml;
        private static string ctxt_formSubmitId;
        private const string newIdMarker = @"separator + ""id=";
        private CRMEntity user;
        private string newAcctId;        
        private string crmServer;
        private string tokenKey;
        private Guid orgId;
        private string name;

        private string referer;
        private WRPCInfo rpcInfo;
        private WebTestRequestHeader headerItem;
    }
}
